﻿using GN.Pay.Client.Impl;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Client.Utils
{
    /// <summary>
    /// 支付配置帮助
    /// </summary>
    public static class PayConfigureUtils
    {
        /// <summary>
        /// AppId 配置名称
        /// </summary>
        public const string AppId_SettingName = "Pay_AppId";
        /// <summary>
        /// AppKey 配置名称
        /// </summary>
        public const string AppKey_SettingName = "Pay_AppKey";
        /// <summary>
        /// MerchantId 配置名称
        /// </summary>
        public const string AppMerchantId_SettingName = "Pay_MerchantId";
        /// <summary>
        /// AppServerUrl 配置名称
        /// </summary>
        public const string AppServerUrl_SettingName = "Pay_ServerUrl";
        
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="appId">应用Id</param>
        /// <param name="appKey">应用Key</param>
        /// <param name="merchantId">应用密文</param>
        /// <param name="serverUrl">服务器Url</param>
        /// <returns></returns>
        public static IPayConfigure CreatePayConfigure(string appId,
            string appKey,
            string merchantId,
            string serverUrl)
        {
            return new PayConfigure(appId, appKey, merchantId, serverUrl);
        }

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="name">名称</param>
        /// <returns></returns>
        public static string GetAppSetting(string name)
        {
            var value = ConfigurationManager.AppSettings.Get(name);
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentException(name, "Config 的 AppSetting 无 " + name + " 节点");
            }
            return value;
        }

        private static IPayConfigure configFileToPayConfigur;

        /// <summary>
        /// 从配置文件生成 IPayConfigure
        /// </summary>
        /// <returns></returns>
        public static IPayConfigure ConfigFileToPayConfigure()
        {
            if (configFileToPayConfigur == null)
            {
                configFileToPayConfigur = CreatePayConfigure(GetAppSetting(AppId_SettingName)
               , GetAppSetting(AppKey_SettingName)
               , GetAppSetting(AppMerchantId_SettingName)
               , GetAppSetting(AppServerUrl_SettingName));
            }
            return configFileToPayConfigur;
        }
    }
}
